package com.sc.social.qq.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

import java.io.IOException;

/**
 * @author sc
 * Created on  2018/1/18
 */
@Slf4j
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private String appId;
    private String openId;

    private ObjectMapper objectMapper = new ObjectMapper();
    /***
     * 获取用户ID的请求
     */
    private static final String URL_GET_OPEN_ID="https://graph.qq.com/oauth2.0/me?access_token=%s";
    /***
     * 获取用户信息
     */
    private static final String URL_GET_USER_INFO="https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    public QQImpl(String accessToken,String appId){
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);
        this.appId=appId;
        String url  = String.format(URL_GET_OPEN_ID,accessToken);
        String result = getRestTemplate().getForObject(url,String.class);
        log.info(result);
        this.openId = StringUtils.substringBetween(result,"\"openid\":\"","\"}");
        log.info("open id:" +openId);
    }

    @Override
    public QQUserInfo getUserInfo()  {
        String url = String.format(URL_GET_USER_INFO,appId,openId);
        String res = getRestTemplate().getForObject(url, String.class);
        log.info("qq  user info:"+res);
        QQUserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(res,QQUserInfo.class);
            userInfo.setOpenId(openId);
        } catch (Exception e) {
            throw new RuntimeException("获取用户信息出错");
        }
        return userInfo;
    }


}
